package org.openmore.opc.controller.api;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.openmore.common.exception.InvalidParamsException;
import org.openmore.common.exception.OpenmoreException;
import org.openmore.opc.controller.BaseController;
import org.openmore.opc.dto.BaseResponse;
import org.openmore.opc.dto.Pagination;
import org.openmore.opc.dto.api.PermissionDto;
import org.openmore.opc.dto.api.RolePermissionDto;
import org.openmore.opc.entity.Permission;
import org.openmore.opc.service.PermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;

/**
 * THIS IS AUTO GENERATED SOURCE CODE
 * Created by org.openmore
 * on 2018-08-09
 */
@Api(value = "/Permission", tags = "Permission", description = "权限")
@RequestMapping(value = "/api/permission", produces = {APPLICATION_JSON_UTF8_VALUE})
@RestController
public class PermissionController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PermissionService permissionService;

    @ApiOperation(value = "分页返回所有数据", response = PermissionDto.class, responseContainer = "List")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：找不到id={id}的Activity", response = PermissionDto.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/query")
    public BaseResponse selectAllByPage(
            @RequestParam(required = false, defaultValue = "all") @ApiParam(value = "权限类型：parent表示父权限，为空或all表示所有权限，children表示子权限") String type,
            @RequestParam(required = false) @ApiParam(value = "权限名称") String name,
            @RequestParam(required = false, defaultValue = "0") @ApiParam(value = "分页第几页") Integer pageNum,
            @RequestParam(required = false, defaultValue = "0") @ApiParam(value = "每页多少记录") Integer pageSize) {
        logger.debug(">> selectAllByPage");
        PageHelper.startPage(pageNum, pageSize);
        List<PermissionDto> resultList = permissionService.selectAll(type, name);
        if (resultList == null) {
            throw new InvalidParamsException("没有数据");
        }
        return BaseResponse.buildSuccessResponse(new Pagination(new PageInfo(resultList)), resultList);
    }

    @ApiOperation(value = "获得权限树", response = PermissionDto.class, responseContainer = "List")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败:原因", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/tree")
    public BaseResponse getPermissionTree() {
        logger.debug(">> getPermissionTree");
        return BaseResponse.buildSuccessResponse(permissionService.getPermissionTree());
    }

    @ApiOperation(value = "根据角色id获得其拥有的权限列表", response = RolePermissionDto.class, responseContainer = "List")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败:原因", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/role/{id}")
    public BaseResponse getGrantedPermissionByRole(@PathVariable @ApiParam(required = true, value = "角色id") String id) {
        logger.debug(">> getGrantedPermissionByRole");
        return BaseResponse.buildSuccessResponse(permissionService.getGrantedPermissionByStaffId(id));
    }

    @ApiOperation(value = "根据id获取Permission信息", response = PermissionDto.class)
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：找不到id={id}的Permission", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public BaseResponse getPermissionById(@PathVariable @ApiParam(required = true, value = "id") String id) {
        logger.debug(">> getPermissionById");
        try {
            PermissionDto permissionDto = permissionService.getDtoById(id);
            if (permissionDto == null) {
                throw new InvalidParamsException("请求失败：找不到id=" + id + "的Permission");
            }
            return BaseResponse.buildSuccessResponse(permissionDto);
        } catch (OpenmoreException e) {
            return BaseResponse.buildFailResponse(400, e.getMsg());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return BaseResponse.buildFailResponse(400, "查询数据失败");
        }

    }

    @Transactional
    @ApiOperation("更新")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：更新的数据不存在", response = BaseResponse.class),
            @ApiResponse(code = 400, message = "请求失败：数据更新失败", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.PUT)
    public BaseResponse updatePermission(@RequestBody @ApiParam(value = "新Permission信息", required = true) PermissionDto permission) {
        logger.debug(">> updatePermission");
        Permission entity = permissionService.getEntityById(permission.getId());
        if (entity == null) {
            throw new InvalidParamsException("请求失败：更新的数据不存在");
        }
        permissionService.update(permission);
        return BaseResponse.buildSuccessResponse("更新成功");
    }

    @Transactional
    @ApiOperation("创建")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：数据创建失败", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.POST, consumes = {APPLICATION_JSON_UTF8_VALUE})
    public BaseResponse insertPermission(@RequestBody @ApiParam(value = "创建Permission", required = true) PermissionDto permission) {
        logger.debug(">> insertPermission");
        PermissionDto permissionDto = permissionService.insert(permission);
        return BaseResponse.buildSuccessResponse(permissionDto);
    }

    @Transactional
    @ApiOperation(value = "删除指定Permission")
    @ApiResponses(value = {@ApiResponse(code = 400, message = "请求失败：数据删除失败", response = BaseResponse.class)})
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    public BaseResponse deletePermission(@PathVariable @ApiParam(value = "Permissionid", required = true) String id) {
        logger.debug(">> deletePermission");
        permissionService.deleteById(id);
        return BaseResponse.buildSuccessResponse("数据删除成功");
    }
}




